<template>
  <div class="cost-adjustment-container">
    <BasicInformation
      title="编辑成本调整"
      :primary-actions="actions"
      @action="handleAction"
    />
    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="120px"
    >
      <el-card class="form-section">
        <template #header>
          <span class="section-title">基础信息</span>
        </template>
        <el-row :gutter="30">
          <el-col :md="12">
            <el-form-item label="编码" prop="code">
              <el-input v-model="form.code" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :md="12">
            <el-form-item label="单据日期" prop="date">
              <el-date-picker
                        v-model="form.date"
                        type="date"
                        placeholder="请选择日期"
                        value-format="YYYY-MM-DD"
                        :disabled-date="disabledDate"
                      />
            </el-form-item>
          </el-col>
          <el-col :md="12">
            <!-- 库管员 -->
                  <el-form-item label="库管员" prop="skid">

                    <el-select
                        v-model="form.skid"
                        placeholder="请选择库管员"
                        style="width: 240px"
                        clearable
                        filterable
                    >
                      <el-option
                          v-for="user in userList"
                          :key="user.id"
                          :label="`${user.name}`"
                          :value="user.id"
                      />
                    </el-select>

                  </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card class="form-section">
        <template #header>
          <div class="section-header">
            <span class="section-title">商品清单</span>
            <el-button type="primary" size="small" @click="goodsDialogVisible = true">
              添加商品
            </el-button>
          </div>
        </template>
        <el-table :data="form.goods" border style="width: 100%">
          <el-table-column prop="code" label="商品编码" />
          <el-table-column prop="name" label="商品名称" />
          <el-table-column prop="kname" label="商品分类" />
          <el-table-column prop="uname" label="商品单位" />
          <el-table-column prop="tax" label="税率" />
          <el-table-column label="调整金额">
            <template #default="{ row, $index }">
              <el-input-number v-model="form.counts[$index]" :step="0.01" />
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <MaterialSelectorDialog
        v-model:modelValue="form.goods"
        v-model:visible="goodsDialogVisible"
      />
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { CostAdjustment, Good } from '@/types/kc/CBTZ'
import BasicInformation from '@/public-view/BasicInformation.vue'
import MaterialSelectorDialog from '@/basic-view/bom/MaterialSelectorDialog.vue'
import type {User} from "@/types/rs/User.ts";
import request from '@/util/request'


const route = useRoute()
const router = useRouter()

const form = reactive<Partial<CostAdjustment>>({
  id: 0,
  code: '',
  date: new Date,
  skid: 0,
  goods: [] as Good[],
  counts: [] as number[],
  delFlag: 0
})

const rules = reactive<FormRules>({
  date: [{ required: true, message: '请选择日期', trigger: 'change' }],
  skid: [{ required: true, message: '请输入 Skid', trigger: 'blur' }]
})

const formRef = ref<FormInstance>()
const goodsDialogVisible = ref(false)
const actions = [
  { name: 'save', label: '保存', type: 'primary' },
  { name: 'reset', label: '重置', type: 'warning' }
]

const disabledDate = (time: Date) => time.getTime() > Date.now()

const getValidCode = () => {
  const raw = route.params.code
  return Array.isArray(raw) ? raw[0] : raw || ''
}

let userList=ref<User[]>([])
let selectUser=async()=>{
  let response=await request.post('per/user/getAll')
  userList.value=response.data.data
  console.log(userList.value)
}
selectUser()

async function loadData() {
  const code = getValidCode()
  if (!code) {
    ElMessage.error('无效编码')
    router.back()
    return
  }
  try {
    const resp = await request.get('kc/proChange/getOne', {
      params: { code }
    })
    if (Number(resp.data.code) === 200) {
      const data: CostAdjustment = resp.data.data
      Object.assign(form, {
        id: data.id,
        code: data.code,
        date: data.date,
        skid: data.skid,
        goods: data.goods,
        counts: data.counts,
        delFlag: data.delFlag,
        typeId :7
      })
    } else {
      ElMessage.error(resp.data.message || '加载失败')
    }
  } catch {
    ElMessage.error('加载异常')
  }
}

onMounted(loadData)

watch(() => route.params.code, loadData)

function handleAction(name: string) {
  if (name === 'save') submitForm()
  else if (name === 'reset') loadData()
}

async function submitForm() {
  try {
    await formRef.value?.validate()
    const payload = JSON.parse(JSON.stringify(form))
    const resp = await request.post(
      'kc/proChange/update',
      payload,
      { headers: { 'Content-Type': 'application/json' } }
    )
    if (Number(resp.data.code) === 200) {
      ElMessage.success('更新成功')
      router.back()
    } else {
      ElMessage.error(resp.data.message || '更新失败')
    }
  } catch {
    ElMessage.error('网络异常')
  }
}
</script>

<style scoped>
.cost-adjustment-container {
  padding: 20px;
}
.form-section {
  margin-bottom: 20px;
}
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.section-title {
  font-size: 16px;
  font-weight: 600;
}
</style>
